#!/bin/bash
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
SFTP_TOOL="$SCRIPT_DIR/../tools/sftp"

# Check if the correct number of arguments is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <version>"
    exit 1
fi

# Get the file name at remote path
if [ ! -f "$SFTP_TOOL" ]; then
    if [ ! -f ./sftp ]; then
        wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
    fi
    chmod +x sftp
    FILE_NAME=$(./sftp list "/hygon-devkit/4.0/2025-01-01/hjdk/$1" | grep -oP "hjdk-.*?\.tar.gz")
else
    FILE_NAME=$($SFTP_TOOL list "/hygon-devkit/4.0/2025-01-01/hjdk/$1" | grep -oP "hjdk-.*?\.tar.gz")
fi
REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/hjdk/$1/$FILE_NAME
LOCAL_DIR=${SCRIPT_DIR}/$1

# Create the local directory if it doesn't exist
mkdir -p "$LOCAL_DIR"
echo "Downloading $REMOTE_PATH to $LOCAL_DIR/$FILE_NAME"

# If the directory don't have the file, download it
if [ -z "$(ls -A "$LOCAL_DIR"/$FILE_NAME 2>/dev/null)" ] ; then
    if [ ! -f "$SFTP_TOOL" ]; then
        ./sftp download "$REMOTE_PATH" $LOCAL_DIR/$FILE_NAME
    else
        $SFTP_TOOL download "$REMOTE_PATH" $LOCAL_DIR/$FILE_NAME
    fi
fi

echo "Extracting $LOCAL_DIR/$FILE_NAME to /opt/hygon"
tar -zxvf $LOCAL_DIR/$FILE_NAME -C /opt/hygon

